﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Linq;
using System.IO;
using MyDMS.DAL;

public partial class _Default : PageBaseClass
{
    private MyDMSEntity _myDmsEntity = new MyDMSEntity();
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Task> lstTasks = _myDmsEntity.Task.Where(t=>t.Assigned_To==Author.user_Code).ToList();
        lsvTasks.DataSource = lstTasks;
        lsvTasks.DataKeyField = "Task_Code";
        lsvTasks.DataBind();

        lsvProjects.DataSource = _myDmsEntity.Project.Where(p => p.Assigned_To == Author.user_Code).ToList();
        lsvProjects.DataKeyField = "Project_Code";
        lsvProjects.DataBind();

        BindTheSD(Author.user_Code);
        BindTheUD(Author.user_Code);

        List<UserMessage> myMsgs = _myDmsEntity.UserMessage.Where(um=>um.User_Code== Author.user_Code).ToList();
        List<InboxMessage> inboxMsgs = new List<InboxMessage>();

        foreach (UserMessage m in myMsgs)
        {
            MailMessage mm = _myDmsEntity.MailMessage.FirstOrDefault(mmm => mmm.Message_Code==m.Message_Code);
            InboxMessage im = new InboxMessage(m);
            im.Message_Subject = mm.Message_Subject;

            inboxMsgs.Add(im);
        }

        gvInbox.DataSource = inboxMsgs;
        gvInbox.DataBind();

    }

    private void BindTheSD(int userCode)
    {
        gvSharedDocuments.DataSource = from ud in _myDmsEntity.UserDocument.Where(ud => ud.User_Code == userCode)
                                       select new
                                                  {
                                                      ud.Shared_Date,
                                                      ud.Share_Comment,
                                                      ud.Document_Code,
                                                      SharedName =
                                           _myDmsEntity.User.FirstOrDefault(u => u.User_Code == ud.Shared_By).FirstName +
                                           _myDmsEntity.User.FirstOrDefault(u => u.User_Code == ud.Shared_By).LastName
                                                  };
        gvSharedDocuments.DataBind();
            gvSharedDocuments.DataBind();
    }

    private void BindTheUD(int userCode)
    {

        gvUploadedDocs.DataSource = from d in _myDmsEntity.Document.Where(ud => ud.Owner == userCode)
                                    select new
                                               {
                                                   d.Document_Name,
                                                   d.Document_Desc,
                                                   d.Document_Code,
                                                   d.Updation_Date,
                                                   TaskName =
                                        _myDmsEntity.Task.FirstOrDefault(t => t.Task_Code == d.Task_Code).Task_Title,
                                                   FolderName =
                                        _myDmsEntity.Folder.FirstOrDefault(f => f.Folder_Code == d.Folder_Code).
                                        Folder_Title
                                               };
            gvUploadedDocs.DataBind();
    }
    protected void gvSharedDocuments_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            //int index = Convert.ToInt32(e.CommandArgument);
            //int documentCode = int.Parse(((GridView)e.CommandSource).Rows[index].Cells[1].Text);

            //Document upDoc = _myDmsEntity.Document.FirstOrDefault(ud => ud.Document_Code == documentCode);
            //DownloadFile(upDoc.File_Path);
            Response.Redirect(string.Format("javascript:window.open( 'viewdocument.aspx?doc={0} ', 'newwin ', 'toolbar=no,menubar=no,status=yes,location=no,resizable=no,scrollbars=yes,width=500,height=380,center:   Yes ');", Convert.ToString(e.CommandArgument)));
        }
    }

    protected void gvUploadedDocs_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            //int index = Convert.ToInt32(e.CommandArgument);
            //int documentCode = int.Parse(((GridView)e.CommandSource).Rows[index].Cells[1].Text);

            //Document upDoc = _myDmsEntity.Document.FirstOrDefault(ud => ud.Document_Code == documentCode);
            //DownloadFile(upDoc.File_Path);
            Response.Redirect(string.Format("javascript:window.open( 'viewdocument.aspx?doc={0} ', 'newwin ', 'toolbar=no,menubar=no,status=yes,location=no,resizable=no,scrollbars=yes,width=500,height=380,center:   Yes ');", Convert.ToString(e.CommandArgument)));
        }
    }

    protected void btnLoadMessage_Click(object sender, EventArgs e)
    {
        int messagecode = int.Parse(hdfItemCode.Value);
        MailMessage m = _myDmsEntity.MailMessage.FirstOrDefault(mm => mm.Message_Code == messagecode);
        lblFrm.Text = m.Owner.ToString();
        lblSubj.Text = m.Message_Subject;
        lblBody.Text = m.Message_Body;
    }

    private void DownloadFile(string filePath)
    {
        //http://dotnetslackers.com/Community/blogs/haissam/archive/2007/04/03/Downloading-Files-C_2300_.aspx

        // Get the physical Path of the file(test.doc)
        //string filepath = );

        // Create New instance of FileInfo class to get the properties of the file being downloaded
        FileInfo file = new FileInfo(filePath);

        // Checking if file exists
        if (file.Exists)
        {
            // Clear the content of the response
            Response.ClearContent();

            // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());

            // Set the ContentType
            Response.ContentType = ReturnExtension(file.Extension.ToLower());

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
            Response.TransmitFile(file.FullName);

            // End the response
            Response.End();
        }
    }

    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
}
